<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Http\Controllers\AdminController;
use App\Models\Themes;
use App\Services\QiniuServices;
use Validator;
use DB;

class ThemeController extends AdminController
{

    public function index()
    {
        return view('admin.theme.index');
    }

    public function data(Request $request)
    {
        $lang = $request->lang??lang();
        $model = Themes::query();
 
		$keyword=$request->get('title');
        if ($keyword) {
			
            $model = $model->where('title', 'like',"%{$keyword}%");
        }
 
        $res = $model->orderBy('id', 'desc')->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return response()->json($data);
    }
 
    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

 

 		$rules= [
            'name' => 'required|unique:defines_translations|max:255',
			'keys'  => 'required|min:2|max:20|unique:defines_translations',
            'value' => 'required',
        ];
		
		$messages = [
			'name' => '配置名 :attribute 称已存在,请换个名称',
			'keys' => 'keys :attribute已存在,请重试!.',
			'value' => '配置值 :attribute不能为空！',
		];
		
		$validator = Validator::make($request->all(), $rules, $messages);

		$errors = $validator->errors();
   
        if ($validator->fails()) {
          return Response::json(['code' => 1, 'msg' => $errors->first(), 'data' => $errors->first(), 'url' => route('admin.theme')]);   
        }

        DB::beginTransaction();
        try {
            $Defines = new Defines();
            $Defines->title = $request->name;
            foreach (config('translatable.locales') as $locale => $item) {
                $Defines->translateOrNew($locale)->group_id = $request->group_id??1;
                $Defines->translateOrNew($locale)->name = $request->name;
                $Defines->translateOrNew($locale)->keys = $request->keys;
                $Defines->translateOrNew($locale)->value = $request->value;

            }
            if($Defines->save() && $this->setServiceProvider($request->keys)){
				
				 DB::commit();
				 return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.theme')]);
			}
        } catch (\Exception $exception) {
            DB::rollback();

        } 


        return response()->json(['code' => 0, 'msg' => '系统错误']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
		$id = (int)$request->id;
        $themes = Themes::findOrFail($id);
        return view('admin.theme.edit', compact('themes'));
    }
	
	
	
    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

		$id = (int)$request->get('id');
		if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
		$data = $request->except(['_token', 'file']);
	 
 		$themes = Themes::where('id',$id)->first();
		$themes->title = $request->title;
		$themes->type = $request->type;
		$themes->themename = $request->themename;
		$themes->thumb = $request->thumb;
		$themes->desc = $request->desc;
		$themes->status = $request->status;
		 
        if ($themes->save()) {
			sysEnv(['WEB_THEME'=>$themes->themename]);
            return response()->json(['code' => 0, 'msg' => '更新成功']);
        }
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

 
    public function updateajax(Request $request)
    {

		$id = (int)$request->id;
		$selected = (int)$request->selected;
		if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
        Themes::where('id','>',0)->update(['selected'=>null]); 
		$themes = Themes::where('id',$id)->first();
		$themes->selected = $selected;
        if ($themes->save()) {
			if($selected==0) sysEnv(['WEB_THEME'=>"default"]); else sysEnv(['WEB_THEME'=>$themes->themename]);;
            return response()->json(['code' => 0, 'msg' => $themes->selected==1?'主题启用成功':'主题取消成功']);
        }
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

 


    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
		
        DB::beginTransaction();
        try { 
            
			//删除云端资源
			foreach($ids as $id){
			  $sonDefines = DefinesTranslation::find($id);	
              $defines = Defines::where('mid',$sonDefines->defines_mid)->first();
				foreach ($defines->translations as $item) {
					$qiniu->objFromDelete($item); 
                    $this->fileDestroy($item->keys);
				}
				$defines->delete();
			}			
			DB::commit();
			\Artisan::call('view:clear');
			return response()->json(['code' => 0, 'msg' => '删除成功']);
		 
		
        } catch (\Exception $exception) {
            DB::rollback();
        }

        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }



 

}
